const util = require('../../utils/util.js')

Page({
    data: {
        orderList: [],
        filteredOrderList: [],
        activeTab: '待完成',
        loading: true,
        Merchantid:null
    },
    onLoad(options) {
        try {
            const userInfo = JSON.parse(decodeURIComponent(options.userInfo));
            this.setData({
                Merchantid: userInfo
            });
        } catch (e) {
            console.error('解析用户信息失败:', e);
            wx.showToast({
                title: '获取用户信息失败',
                icon: 'none'
            });
        }
        this.loadOrderList();
    },

    // 加载订单列表
    loadOrderList() {
        wx.showLoading({
            title: '加载中...',
        });

        this.setData({
            loading: true
        });
        const url = this.data.Merchantid 
        ? `/order/M_list?merchantId=${this.data.Merchantid}` 
        : '/order/M_list';

        util.callContainerApi(url,"GET",null)
        .then(res => {
            if (res.data && res.data.data) {
                // 处理订单数据
                const processedOrders = this.processOrderData(res.data.data);

                this.setData({
                    "orderList": processedOrders,
                    loading: false
                });

                this.filterOrders();
            } else {
                this.setData({
                    "orderList": [],
                    loading: false
                });
            }
            wx.hideLoading();
        }).catch(err => {
            console.error('获取订单列表失败', err);
            wx.hideLoading();
            wx.showToast({
                title: '获取订单失败',
                icon: 'error'
            });
            this.setData({
                loading: false
            });
        });
    },

    // 处理订单数据
    processOrderData(orders) {
        return orders.map(order => {
            // 格式化创建时间
            if (order.createAt) {
                order.createTime = util.formatTime(order.createAt);
            }
            // 获取商品预览信息
            if (order.childs && order.childs.length > 0) {
                const firstGoods = order.childs[0];
                order.goodsPreview = {
                    name: firstGoods.merchandiseName || '商品名称',
                    spec: firstGoods.specDesc || '',
                    price: firstGoods.singlePrice || 0,
                    count: firstGoods.num || 1,
                    image: firstGoods.file_id || firstGoods.fild_id || '/images/default-goods.png'
                };
                order.goodsCount = order.childs.length;
            }

            return order;
        });
    },

    onShow() {
        this.filterOrders()
    },
    
    filterOrders() {
        const { orderList, activeTab } = this.data;
        let filteredOrderList = [];
        
        switch (activeTab) {
            case '待完成':
                // 待完成状态包括原来的 Create、Payed、Accept、Send 状态
                filteredOrderList = orderList.filter(order => 
                    ['Payed', 'Accept', 'Send'].includes(order.status)
                );
                break;
            case '已完成':
                filteredOrderList = orderList.filter(order => order.status === 'Finish');
                break;
        }
        
        this.setData({
            "filteredOrderList": filteredOrderList
        });
    },
    
    onTabChange(e) {
        const activeTab = e.currentTarget.dataset.tab;
        this.setData({
            activeTab
        });
        this.filterOrders();
    },
    
    // 显示订单详情
    showOrderDetail(e) {
        const orderId = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: `/pages/orderDetail/orderDetail?id=${orderId}`,
        })
    },
    
    
    // 确认收货 - 现在是将订单状态从待完成变为已完成
    confirmReceipt(e) {
        const orderId = e.currentTarget.dataset.id
        util.callContainerApi(`/order/finish?orderId=${orderId}`,"POST",null)
        .then(res => {
            console.log(res)
            wx.showToast({
                title: '订单已完成',
                icon: 'success'
            });
            this.loadOrderList()
        })
    },

    // 下拉刷新
    onPullDownRefresh() {
        this.loadOrderList();
        setTimeout(() => {
            wx.stopPullDownRefresh();
        }, 1000);
    }
});